<?php

class MainController extends Controller {

    public $redirect301 = [
        '/news/onlayn-translyaciya-servis-centrov' => '/online-broadcast',
    ];

    function pc_validate($user, $pass) {
        /* replace with appropriate username and password checking,
          such as checking a database */
        $users = array('admin' => 'mobix8',
            'dilshod' => 'bekorchi');

        if (isset($users[$user]) && ($users[$user] == $pass)) {
            return true;
        } else {
            return false;
        }
    }
	
	public function actionReport($peer, $message) {	
		ini_set("display_errors", 1);
		error_reporting(E_ALL);
		Yii::app()->telegram->getImage($message);
	}

    public function actionSendReview() {
        ini_set("display_errors", 1);
        error_reporting(E_ALL);
        if (!$this->pc_validate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
            header('WWW-Authenticate: Basic realm="My Website"');
            header('HTTP/1.0 401 Unauthorized');
            echo "You need to enter a valid username and password.";
            exit;
        }
        //echo 'ip: ', mTools::getUserIp(), '<br>';
        $aPath = Yii::app()->theme->baseUrl . '/assets';
        echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>';
        echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" media="all"/>';
        echo '<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>';
        $sql = "SELECT Name FROM tblKadr WHERE Uvolen5120558000=0 AND NAme like '%]%' AND NAme not like '%SYS%'";
        $users = Yii::app()->dbDest->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        array_walk_recursive($users, function(&$value, &$key) {
            $value = iconv("CP1251", "UTF-8", $value);
        });
        $h = '';
        foreach ($users as $user) {
            $h .= '<option value="' . $user['Name'] . '">' . $user['Name'] . '</option>';
        }
        echo '<form>'
        . '<select name="user">' . $h
        . '</select><br />'
        . '<textarea cols=30 rows=20 name="comment"></textarea> <br /><input type="submit" value="Отправить">'
        . '</form>';
        if (Yii::app()->user->hasFlash('success')) {
            echo '<br /><p>' . Yii::app()->user->getFlash('success') . '</p>';
        }
        echo '<script>$("select").css("width", "14%").select2();</script>';
        if (!empty($_GET['user']) && !empty($_GET['comment'])) {
            $data = array('user' => $_GET['user'], 'comment' => $_GET['comment'], 'date' => time());
            Yii::app()->db->getCommandBuilder()->createInsertCommand('mb_comments', $data)->execute();
            Yii::app()->user->setFlash('success', 'Ваше предложение принято успешно.');
            $this->redirect('/reviews');
        }
    }

    public function actionPartners() {
        $this->pageTitle = 'Для партнерам — Моби03';
        Controller::$pageData['pageTitle'] = 'Партнерам';
        $model = new SuppliersForm();
        $model->attributes = Yii::app()->session['userAttributes'];
        if (isset($_POST['SuppliersForm'])) {
            Yii::app()->session['userAttributes'] = $_POST['SuppliersForm'];
            $model->attributes = $_POST['SuppliersForm'];
            $msg = 'Имя: <strong>' . $model->userName . '</strong>' .
                    '<br />' . 'Телефон: <a href="tel:' . preg_replace("/\D/", "", $model->userPhone) . '">' . $model->userPhone . '</a>' .
                    '<br />' . 'E-mail: ' . $model->userEmail .
                    '<br />' . 'Описание: ' . $model->note .
                    '<br />' . 'Ссылка на сайт: ' . $model->vacancyUrl;
            mTools::sendMail('x8.sultanov@gmail.com', 'Новое предложение о партнерстве.', $msg);
            Yii::app()->user->setFlash('success', ['Поздравляем!', 'Ваше предложение принято успешно. Ответ получите в кратчайшие сроки.']);
            $this->refresh();
        }
        $this->render('partners', array('model' => $model));
    }

    public function actionSupplier() {
        if (empty(Controller::$pageData['pageLanguage']))
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        $this->pageTitle = 'Для поставщиков — Моби03';
        $model = new SuppliersForm();
        $model->attributes = Yii::app()->session['userAttributes'];
        if (isset($_POST['SuppliersForm'])) {
            Yii::app()->session['userAttributes'] = $_POST['SuppliersForm'];
            $model->attributes = $_POST['SuppliersForm'];
            $uploadedFile = CUploadedFile::getInstance($model, 'resume');

            $msg = 'Имя: <strong>' . $model->userName . '</strong>' .
                    '<br />' . 'Фамилия: <strong>' . $model->userFamily . '</strong>' .
                    '<br />' . 'Название компании: <strong>' . $model->userCompany . '</strong>' .
                    '<br />' . 'Телефон: <a href="tel:' . preg_replace("/\D/", "", $model->userPhone) . '">' . $model->userPhone . '</a>' .
                    '<br />' . 'E-mail: ' . $model->userEmail .
                    '<br />' . 'Примечание: ' . $model->note .
                    '<br />' . 'Ссылка на сайт: ' . $model->vacancyUrl;

            mTools::sendMail('supply@mobi03.ru', 'Новое предложение о партнерстве.', $msg, $uploadedFile);
            Yii::app()->user->setFlash('success', ['Поздравляем!', 'Ваше предложение принято успешно. Ответ получите в кратчайшие сроки.']);
            $this->refresh();
        }
        $this->render('supplier', array('model' => $model));
    }

    public function actionLunch($key) {
        $mainKey = 258555;
        if ($key != $mainKey)
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        $criteria = new CDbCriteria();
        $date = isset($_GET['date']) ? $_GET['date'] : date('d-m-Y');
        $arrDate = explode('-', $date);
        $criteria->order = 'lunch_time';
        $criteria->addCondition('ldate_day = ' . $arrDate[0] . ' AND ldate_month = ' . $arrDate[1] . ' AND ldate_year = ' . $arrDate[2]);
        $selecteds = AppLunch::model()->findAll($criteria);
        $users = CHtml::listData($selecteds, 'log_id', 'user_id');
        $unselecteds = AppUsers::model()->findAll('user_id NOT IN(' . implode(',', $users) . ')');
        $this->render('lunch', array('selecteds' => $selecteds, 'unselecteds' => $unselecteds, 'date' => $date, 'mainKey' => $mainKey));
    }

    public function actionRedirect() {
        $this->render('redirect');
//        $this->redirect('http://clck.yandex.ru/redir/dtype=stred/pid=47/cid=1248/*http://market.yandex.ru/shop/102286/reviews/add');
    }

    public function actionWin() {
        $query = $_GET['query'];
        echo json_encode(Yii::app()->db->getcommandBuilder()->createSqlCommand($query)->queryAll());
    }

    public function actionIndex() {
        //Yii::app()->request->enableCsrfValidation = false;
        if (isset($_POST['token'])) {
            $s = file_get_contents('http://ulogin.ru/token.php?token=' . $_POST['token'] . '&host=' . $_SERVER['HTTP_HOST']);
            $userN = json_decode($s, true);
//			print_r($userN);exit;
            $user = Users::model()->find('LOWER("userEmail")=:userEmail', array(':userEmail' => strtolower($userN['email'])));
            if ($user === null) {
                $user = new Users();
                $user->userName = $userN['first_name'] . ' ' . $userN['last_name'];
                $user->userEmail = $userN['email'];
                $user->userAuthType = $userN['network'];
                $user->userPassword = Users::hashPassword($userN['email'], '123');
                $user->userActive = 1;
                $user->save(false);
            }
            $identity = new UserIdentity($user->userEmail, $user->userPassword);
            if ($identity->authenticate(true))
                Yii::app()->user->login($identity);
            else
                echo $identity->errorMessage;
            $this->refresh();
        }

        foreach (Yii::app()->params['regions'] as $key => $value) {
            $regions[] = $value['genitive'];
        }
        $regions = implode(', ', $regions);
        $this->pageTitle = 'Срочный ремонт ноутбуков и сотовых телефонов, компьютерная помощь в ' . $regions . ' — Моби03';
        Yii::app()->clientScript->registerMetaTag('Мы осуществляем ремонт ноутбуков и компьютеров, сотовых телефонов, планшетов, фотоаппаратов и другой цифровой техники. 17 филиалов по России. Прайс-лист. Аудио отзывы клиентов.', 'description');
        Yii::app()->clientScript->registerMetaTag('ремонт ноутбуков, ремонт телефонов, компьютерная помощь', 'keywords');
        $this->render('index');
    }

    public function actionSavePayment() {
        if (isset($_POST) && !empty($_POST)) {
            $data = $_POST;

            $file = fopen("/var/www/mobi03/data/www/mobi03.ru/uploads/payments.php", "a");
            fwrite($file, $result . chr(13) . "lastINSERT:" . $payId . chr(13));
            fclose($file);

            $payment = array(
                'paymentMerchantId' => $data['LMI_MERCHANT_ID'],
                'paymentSystem' => $data['LMI_PAYMENT_SYSTEM'],
                'paymentCurrency' => $data['LMI_CURRENCY'],
                'paymentAmount' => $data['LMI_PAYMENT_AMOUNT'],
                'paymentDescription' => $data['LMI_PAYMENT_DESC'],
                'paymentDate' => $data['LMI_SYS_PAYMENT_DATE'],
                'paymentLmiId' => $data['LMI_SYS_PAYMENT_ID'],
                'paymentPaidAmount' => $data['LMI_PAID_AMOUNT'],
                'paymentPaidCurrency' => $data['LMI_PAID_CURRENCY'],
                'paymentSimMode' => $data['LMI_SIM_MODE'],
                'paymentPayerId' => $data['LMI_PAYER_IDENTIFIER'],
                'paymentMethod' => $data['LMI_PAYMENT_METHOD'],
                'paymentHash' => $data['LMI_HASH'],
            );
            $nPayment = new Payments;
            $nPayment->attributes = $payment;
            $nPayment->save(false);

            //Yii::app()->db->getCommandBuilder()->createInsertCommand( '{{payments}}', $payment )->execute();
            $payId = $nPayment->paymentId;
            $desc = explode(";", $payment['paymentDescription']);
            $orderNo = str_replace(" ", '', str_replace('Оплата по заказу №: ', '', $desc[0]));
            $orderSc = trim(str_replace('СЦ: ', '', $desc[1]));

            $orderSum = $payment['paymentPaidAmount'];
            $delimiter = ', ';
            $description = "ID: " . $payId . $delimiter .
                    "Id платежа с PM: " . $payment['paymentpaymentMerchantId'] . $delimiter .
                    "Система оплаты: " . $payment['paymentSystem'] . $delimiter .
                    "Описание: " . $payment['paymentDescription'] . $delimiter .
                    "ID: " . $payment['paymentLmiId'] . $delimiter .
                    "ID: " . $payment['paymentPayerId'] . $delimiter .
                    "ID: " . $payment['paymentMethod'] . $delimiter .
                    "ID: " . $payment['paymentHash'];
            $url = 'http://erp.mobi03.ru/6878/requestPayments.ashx?requestNumber=' . $orderNo . '&action=add&amount=' . $orderSum . '&vidPlateja=' . urlencode('За ремонт') . '&description=' . urlencode($description) . '&sc=' . urlencode($orderSc);

            $result = json_decode(file_get_contents($url), true);

            if (isset($result['response']) && $result['response'] == 'success') {
                $sql = "UPDATE {{payments}} SET \"paymentSimMode\"='Отправлено в Кларис' WHERE \"paymentId\"=" . $payId;
            } else {
                $sql = "UPDATE {{payments}} SET \"paymentSimMode\"='Ошибка при отправки в Кларис' WHERE \"paymentId\"=" . $payId;
            }
            /*
             * unset($nPayment);
              $nPayment = Payments::model()->findByAttributes( ['paymentId' => $payId ] );
              if ( !empty( $nPayment ) )
              {
              $nPayment->paymentSimMode = $result;
              $nPayment->save( false );
              } */
            Yii::app()->db->createCommand($sql)->execute();
        }
    }

    public function actionGenerateXmlClaris() {

        header("content-type:text/xml;charset=utf-8");

        if (!isset($_REQUEST['model']))
            return;

        $model = (int) $_REQUEST['model'];

        if (!isset($_REQUEST['region']))
            $region = 1;
        else
            $region = (int) $_REQUEST['region'];

        $sql = ' SELECT "serviceId", "serviceTitle", price FROM {{_model2serv_all}} WHERE "modelId" = ' . $model . ' AND "regionId" =  ' . $region;

        $dServices = Yii::app()->db->createCommand($sql)->queryAll(true);

        $xml = new DomDocument('1.0', 'utf-8');

        $mobi = $xml->createElement('mobi03_ru');

        $xml->appendChild($mobi);

        $request = $xml->createElement('request_code');

        $mobi->appendChild($request);

        if ($dServices) {


            $request->appendChild($xml->createTextNode('200'));

            $services = $xml->createElement("services");

            $mobi->appendChild($services);

            foreach ($dServices as $row) {
                $item = $xml->createElement('item');

                $id = $xml->createAttribute("id");
                $id->appendChild($xml->createTextNode($row['serviceId']));
                $item->appendChild($id);

                $name = $xml->createAttribute("name");
                $name->appendChild($xml->createTextNode($row['serviceTitle']));
                $item->appendChild($name);

                $price = $xml->createAttribute("price");
                $price->appendChild($xml->createTextNode((int) $row['price']));
                $item->appendChild($price);

                $services->appendChild($item);
            }
        } else {
            $request->appendChild($xml->createTextNode('404'));
        }

        echo $xml->saveXML();

        exit();
    }

    public function actionSitemap() {

        header('content-type:text/xml');

        echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\r\n";

        $sql = " SELECT \"pageUrl\" FROM {{pages}} WHERE \"pageActive\"=1 ORDER BY \"pageId\";";
        $pages = Yii::app()->db->createCommand($sql)->queryAll(true);

        if ($pages) {
            foreach ($pages as $page) {
                echo "<url>\r\n<loc>" . Yii::app()->request->hostInfo . '/' . $page['pageUrl'] . "</loc>\r\n<lastmod>" . date("Y-m-d", time()) . "</lastmod>\r\n<changefreq>daily</changefreq>\r\n<priority>0.8000</priority>\r\n</url>\r\n";
            }
        }

        $sql = " SELECT \"faqUrl\" FROM {{faq}} WHERE \"faqStatus\"=1 AND \"faqUrl\" IS NOT NULL AND \"faqType\"='question' ORDER BY \"faqId\";";
        $faqs = Yii::app()->db->createCommand($sql)->queryAll(true);

        if ($faqs) {
            foreach ($faqs as $faq) {
                echo "<url>\r\n<loc>" . Yii::app()->request->hostInfo . '/' . $faq['faqUrl'] . "</loc>\r\n<lastmod>" . date("Y-m-d", time()) . "</lastmod>\r\n<changefreq>daily</changefreq>\r\n<priority>0.8000</priority>\r\n</url>\r\n";
            }
        }

        echo "</urlset>";

        exit();
    }

    public function actionError() {
        $this->pageTitle = 'Страница не найдена 404';
        header("HTTP/1.0 404 Not Found");
//        
//        if ($error = Yii::app()->errorHandler->error) {
//            echo $error['message'];
//        }
//        
//        exit;
        foreach ($this->redirect301 as $oldUrl => $redirectUrl) {
            if (strtolower(Yii::app()->request->url) == strtolower($oldUrl)) {
                Controller::redirect('/online-broadcast', true, 301);
            }
        }

        $this->render('error');
    }

    public function actionAutoLogin() {
        $identity = new UserIdentity('new@new.ru', '111111');
        if ($identity->authenticate(false))
            Yii::app()->user->login($identity);
        else
            echo $identity->errorMessage;
        if (!Yii::app()->user->isGuest) {
//            Yii::app()->user->setFlash('success', ['Поздравляем!', 'Ваше предложение принято успешно. Ответ получите в кратчайшие сроки.']);
            $this->redirect('/');
        }
    }

}
